<?php

class App_Model_DbTable_Buddy extends Ext_Db_Table  
{  
    /** Table name */  
    protected $_name = 'buddy';
    
    private static $_buddyRow = array();
    
    public function getRowById($id)
    {
        if(!$id)
        {
            return "";
        }
        
        if(isset(self::$_buddyRow['id'][$id]))
        {
            return self::$_buddyRow['id'][$id];
        }
        
        $db = $this->getAdapter();
        $safe = $db->quoteInto(" id = ? ", $id);
        $row = $this->fetchRow($safe);

        if (!$row) {
            return "";
        }
        
        $_buddyRow = $row->toArray();
        
        self::$_buddyRow['id'][$id] = $_buddyRow;
        $_userId = $_buddyRow['userId'];
        $_buddyUserId = $_buddyRow['buddyUserId'];
        if($_userId && $_buddyUserId)
        {
            self::$_buddyRow['userId']['buddyUserId'][$_userId][$_buddyUserId] = $_buddyRow;
        }
        
        return $_buddyRow;
    }
    
    public function getRowByUserIdBuddyUserId($userId, $buddyUserId)
    {
        if(!$userId || !$buddyUserId)
        {
            return "";
        }
        
        if(isset(self::$_buddyRow['userId']['buddyUserId'][$userId][$buddyUserId]))
        {
            return self::$_buddyRow['userId']['buddyUserId'][$userId][$buddyUserId];
        }
        
        $db = $this->getAdapter();
        $select = $db->select();
        $select
            ->from($this->_name, "id")
            ->where('userId = :userId AND buddyUserId = :buddyUserId')
            ->limit(1)
            ;
        $params = array('userId' => $userId, 'buddyUserId' => $buddyUserId);
        $select->bind($params);
        
        $row = $db->fetchRow($select);
        if(!$row) {
            return "";
        }
        $_buddyRow = $row;
        
        self::$_buddyRow['userId']['buddyUserId'][$userId][$buddyUserId] = $_buddyRow;
        $_id = $_buddyRow['id'];
        if($_id)
        {
            self::$_buddyRow['id'][$_id] = $_buddyRow;
        }
        
        return $_buddyRow;
    }
    
    public function del($id)
    {
        $db = $this->getAdapter();
        $safe = $db->quoteInto(" id = ? ", $id);
        $rows_affected = $this->delete($safe);

        return "";
    }
    
    public function addNew($inputArray)
    {
        $row = array (
            'userId'                 => $inputArray['userId'],
            'buddyUserId'            => $inputArray['buddyUserId'],
            'createTime'             => time(),
        );

        try {
            $rows_affected = $this->insert($row);
            $last_insert_id = $this->getAdapter()->lastInsertId();
        }catch (Exception $e){
            trigger_error($e->getMessage(), E_USER_WARNING);
        }
        return $last_insert_id;
    }
    
    
}  

